<template>
  <div class="wrap">
    <select-platform v-model="queryParams.platformType" @change="changePlatform" :num-arr="numArr" :platform-type="queryParams.platformType" :show-packet="true"></select-platform>
    <div class="header">
      <div class="left">
        <el-select
          v-model="queryParams.status"
          class="mgr20 mgb10"
          size="small"
          style="margin-left: 0"
          @change="changeOption"
          clearable>
          <el-option :label="$t('picking.All states')" value=""></el-option>
          <el-option :label="$t('picking.Goods to be picked')" :value="0"></el-option>
          <el-option :label="$t('picking.Picked')" :value="1"></el-option>
        </el-select>

        <el-select
          v-model="queryParams.pickingLogisticsType"
          class="mgr20 mgb10"
          size="small"
          style="margin-left: 0"
          @change="changeOption"
          v-if="queryParams.platformType !== 7"
          clearable>
          <el-option :label="$t('picking.All type')" value=""></el-option>
          <el-option :label="$t('picking.Deck sheet')" :value="1"></el-option>
          <el-option :label="$t('picking.Logistics sheet')" :value="2"></el-option>
        </el-select>

        <el-date-picker
          v-model="queryParams.times"
          type="daterange"
          class="mgr20 mgb10"
          :start-placeholder="$t('common.startDate')"
          :end-placeholder="$t('common.endDate')"
          value-format="yyyy-MM-dd"
          @change="changeOption"
        >
        </el-date-picker>

        <div style="display: inline-block">
          <el-input
            size="small"
            style="width: 280px; margin-right: 10px; margin-bottom: 10px"
            v-model="queryParams.keyword"
            :placeholder="$t('picking.Search for tracking number/order number/Listing ID/SKU')"
            @keyup.enter.native="changeOption(true)"
            clearable @clear="changeOption(false, 'clear')"></el-input>
          <el-button size="small" type="primary" icon="el-icon-search" @click="changeOption(true)"></el-button>
        </div>

      </div>

      <div class="right">

      </div>
    </div>
    <div class="content">
      <el-table
        class="el-table"
        :data="data"
        row-key="id"
        border
        v-loading="loading"
        @selection-change="handleSelectionChange"
        :row-class-name="tableRowClassName"
        @sort-change="handleSortChange"
        v-tableHeight="{bottomOffset: 80}"
        height="100px"
        ref="tableData"
      >
        <el-table-column
          type="selection"
          align="center"
          width="50"
          :selectable="selectable"
          fixed="left"
        >
        </el-table-column>
        <el-table-column
          prop="pickingNo"
          :label="$t('table.Picking list')"
          align="center"
          width="200"
          fixed="left"
        >
          <template slot-scope="{row}">
            <diy-link @click="jumpInfo(row)">{{row.pickingNo}}</diy-link>
          </template>
        </el-table-column>
        <el-table-column
          prop="user"
          :label="$t('table.user name')"
          align="center"
          width="200"
          v-if="false"
        >
          <template slot-scope="{row}">
            <div
              v-for="user in row.userList"
              :key="user.userId"
            >
              {{user.account}}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="accountList"
          :label="$t('table.shopNames')"
          align="center"
          min-width="300"
          v-if="false"

        >
          <template slot-scope="{row}">
            <div
              v-for="account in row.accountList"
              :key="account.accountId"
            >
              {{account.showName}}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="orderNum"
          :label="$t('table.Order Quantity')"
          align="center"
          width="160"
          sortable="custom"
          :sort-orders="sortOrders"
        >
        </el-table-column>
        <el-table-column
          prop="skuNum"
          :label="$t('table.types(SKU)')"
          align="center"
          width="160"
          sortable="custom"
          :sort-orders="sortOrders"
        >
        </el-table-column>
        <el-table-column
          prop="goodsNum"
          :label="$t('table.productQuantity')"
          align="center"
          width="180"
          sortable="custom"
          :sort-orders="sortOrders"
        >
        </el-table-column>
        <el-table-column
          prop="status"
          :label="$t('table.status')"
          align="center"
          width="200"
        >
          <template slot-scope="{row}">
            {{row.status === 0 ? $t('picking.Goods to be picked') + `(${row.currentPickNum}/${row.totalPickNum})` : $t('picking.Picked')}}
          </template>
        </el-table-column>
        <el-table-column
          prop="pickingLogisticsType"
          :label="$t('table.type')"
          align="center"
          width="200"
        >
          <template slot-scope="{row}">
            {{row.pickingLogisticsType === 1 ? $t('picking.Deck sheet') : $t('picking.Logistics sheet')}}
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          :label="$t('table.createTime3')"
          align="center"
          width="200"
        >
        </el-table-column>
        <el-table-column
          prop="firstDownload"
          :label="$t('picking.Shipping (first time) download')"
          align="center"
          width="200"
        >
          <template slot-scope="{row}">
            {{row.firstDownload || '-'}}
          </template>
        </el-table-column>
        <el-table-column
          prop="num"
          :label="$t('table.operate')"
          align="left"
          min-width="320"
          fixed="right"
        >
          <template slot-scope="{row}">
            <el-button type="view" plain @click="jumpInfo(row)">{{ $t('common.detail') }}</el-button>
            <template v-if="row.status === 0">
            </template>
            <el-button type="primary" @click="showPDFDialog(row)" :loading="row.jhLoading">{{$t('picking.Export picking list')}}</el-button>
            <template v-if="row.pickingLogisticsType === 2">
              <LogisticsPickingButton
                :pickingType="'all'"
                :pickingOrderData="row"
                :integratedLogisticsSettingData="integratedLogisticsSettingData"
                :defaultLogisticsType="defaultLogisticsType"
                :pickingLogisticsType="row.pickingLogisticsType"
                @changeOrder="changeOrder"
                @lableDialog="lableDialog"
                style="display: inline"
                class="mgl10"
              ></LogisticsPickingButton>
            </template>
            <template v-else>
              <el-button :type="row.status === 1  ? 'success' :'danger' " @click="downLoadShipping(row)" :loading="row.shippingLoading" v-if="row.canShipping || isTesting()">{{$t('order.downloadShipping')}}</el-button>
            </template>
          </template>
        </el-table-column>

      </el-table>

      <div style="height: 30px;" class="mgt10">
        <el-pagination
          style="display: inline-block"
          @current-change="getData"
          :current-page.sync="queryParams.page"
          :page-size.sync="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100, 500, 1000]"
          :total="total"
          @size-change="handleSizeChange"
          layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>
        <div style="display: inline-block;padding-top: 5px;" class="mgl20">
          <el-button
            :disabled="!(selectRow.length > 0 && selectRow.some(item => item.status === 0))"
            type="primary"
            :loading="printLoading"
            @click="showPDFDialog(null)"
            style="height: 30px; position: relative; top: 5px;">{{$t('picking.Export Selected')}}</el-button>
          <el-button
            :disabled="!(selectRow.length > 0 && selectRow.some(item => item.canShipping))"
            @click="batchShipping"
            type="danger"
            :loading="batchLoading"
            style="height: 30px; position: relative; top: 5px;">{{ $t('order.downloadSelectedShipping') }}</el-button>
        </div>
      </div>

    </div>


    <el-dialog :title="$t('picking.exportTitle')" :visible.sync="PDFDialog" width="400px">
      <div style="margin-top: -15px">
        <el-radio v-model="currentPDFForm.PDFType" :label="1" class="mgb10">{{$t('picking.exportRadio1')}}</el-radio>
        <br>
        <el-radio v-model="currentPDFForm.PDFType" :label="2">{{$t('picking.exportRadio2')}}</el-radio>
      </div>
      <div slot="footer" class="dialog-footer" style="margin-top: -15px">
        <el-button @click="PDFDialog = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="batchPickPDF" :loading="printLoading">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :title="$t('picking.正在生成面单中,请耐心等待')"
      :visible.sync="lableDialogVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      width="60%"
    >
      <el-container>
        <el-header>
          <div class="left">
            <el-alert type="error" :closable="false">{{ $t('picking.所有包裹面单生成完毕后即可一键全部下载，您也可以单独下载已生成状态包裹的面单') }}</el-alert>
          </div>
          <div class="right" style="float: right;margin-top: 10px;" >
          <LogisticsPickingButton
            :is-button-all-disabled="picking.status == 1 ? false :true"
            :pickingType="'all'"
            :pickingOrderData="picking"
            :integratedLogisticsSettingData="integratedLogisticsSettingData"
            :defaultLogisticsType="defaultLogisticsType"
            :pickingLogisticsType="picking.pickingLogisticsType"
            @changeOrder="changeOrder"
            @closeLableDialogVisible="closeLableDialogVisible"

            style="display: inline"
            class="mgr10"
          ></LogisticsPickingButton>
          </div>
        </el-header>
        <el-main>
          <el-table :data="detailData" border style="width: 100%;margin-top: 10px;">
            <el-table-column prop="orderId" :label="$t('table.orderId')" align="center" width="170"></el-table-column>
            <el-table-column prop="tracking_number" :label="$t('picking.物流商')" align="center" width="210">
              <template slot-scope="{ row }">
                <template v-if="row.tracking_number === ''">-</template>
                <template v-else>{{ row.tracking_number_type }}</template>
              </template>
            </el-table-column>

            <el-table-column prop="tracking_number" :label="$t('common.物流单号')" align="center" width="210" :show-overflow-tooltip="true">
             <template slot-scope="{ row }">
               <template v-if="row.tracking_number === ''&&row.logisticsErrorMsg === ''">-</template>
               <template v-else-if="row.logisticsErrorMsg === ''&&row.tracking_number != ''">{{ row.tracking_number_type }}-{{ row.tracking_number }} </template>
               <template v-else><p style="color: red;">生成失败：{{row.logisticsErrorMsg}}</p></template>
             </template>
            </el-table-column>
            <el-table-column prop="stickerStatus" :label="$t('picking.状态')" align="center" width="150">
              <template slot-scope="{ row }">
                <template v-if="picking.pickingLogisticsType === 2" >
                  <template v-if="row.tracking_number===''&&row.logisticsErrorMsg!= ''">
                     生成失败
                  </template>
                  <template v-else>
                     <i class="el-icon-loading" style="color:blue" v-if="row.tracking_number===''"></i>
                    {{ row.tracking_number !== '' ? $t('picking.已生成') :$t('picking.生成中') }}
                  </template>
                </template>
                <template v-else>
                  {{ row.stickerStatus ? (row.isScan ? $t('picking.Picked') : '/') : $t('picking.Goods to be picked') }}
                </template>
              </template>
            </el-table-column>
            <template v-if="picking.pickingLogisticsType === 2">
              <el-table-column prop="num" :label="$t('table.operate')" align="center" min-width="250">
                <template slot-scope="{ row }">
                  <LogisticsPickingButton
                    :is-button-disabled="row.tracking_number !== '' ? false :true"
                    :pickingType="'single'"
                    :pickingOrderData="row"
                    :integratedLogisticsSettingData="integratedLogisticsSettingData"
                    :defaultLogisticsType="defaultLogisticsType"
                    :pickingLogisticsType="picking.pickingLogisticsType"
                    style="display: inline;"
                  ></LogisticsPickingButton>
                </template>
              </el-table-column>
            </template>

          </el-table>
        </el-main>
      </el-container>
    </el-dialog>
  </div>
</template>

<script>
import {batchPickPDF, batchSurePicking, getPickingList, printPickShipping, surePicking,getPickingInfo} from "@/api/picking";
import {printShipping} from "@/api/order";
import {deepCopy} from "@/utils";
import {isTesting} from "@/utils/common";
import SelectPlatform from "@/components/SelectPlatform/index.vue";
import LogisticsPickingButton from "@/views/order/components/LogisticsPickingButton.vue";

export default {
  name: "packList",
  components: {
    SelectPlatform,
    LogisticsPickingButton,
  },
  data(){
    return {
       interval: null,
      detailData:[],
      picking: {
        id: '',
        pickingNo: '',
        status: '',
        pdfStatus: 0,
        currentNum: 0,
        totalNum: 0,
        canShipping: false,
        isKnowFail: 0, // 是否知道失败
        failStatus: 0, // 0没有失败 1部分失败 2全失败了
        pickingLogisticsType: 1
      },
       lableDialogVisible: false,
      queryParams: {
        page: 1,
        pageSize: 20,
        times: [],
        status: '',
        pickingLogisticsType: '',
        keyword: '',
        platformType: this.$store.getters.defaultAccountTypeNum,
        orderBy: '',
        orderField: '',
      },
      data: [],
      loading: false,
      total: 0,
      selectIds: [],
      selectRow: [],
      batchLoading: false,
      PDFType: 1,
      printLoading: false,
      PDFDialog: false,
      currentPDFForm:{
        pickIds: [],
        PDFType: 1,
      },
      numArr: [],
      is_search: false,
      sortOrders: ['descending', 'ascending', null],
      shippingPDFLoading: false,
      integratedLogisticsSettingData: [],
      defaultLogisticsType: '',
    };
  },
  created() {
    this.getData()
  },
  updated () {
    this.$nextTick(() => {
      this.$refs['tableData'].doLayout();
    })
  },
  beforeDestroy() {
    if (this.interval) {
      clearInterval(this.interval);
    }
  },
  methods:{
    isTesting,
    getData(){
      this.loading = true;
      getPickingList(this.queryParams)
        .then(res=>{
          this.loading = false;
          this.data = []
          res.data.forEach(item=>{
            const obj = deepCopy(item)
            obj.shippingLoading = false // 面单pdf
            obj.jhLoading = false // 拣货pdf
            this.data.push(obj)
          })
          this.total = res.info.total
          this.numArr = res.info.platformNum;
          this.integratedLogisticsSettingData = res.info.integratedLogisticsSettingData;
          this.defaultLogisticsType = res.info.defaultLogisticsType;
        })
    },
    closeLableDialogVisible(){
      this.lableDialogVisible=false
    },
    //循环查询订单的物流状态
    lableDialog(row) {
      this.lableDialogVisible = true;

      this.loopGetLableData(row);
    },
    //请求包裹下载面单
    loopGetLableData(row) {
    getPickingInfo(row.pickingNo).then((res) => {
         this.picking.id = res.data.id;
         this.picking.pickingNo = res.data.pickingNo;
         this.picking.status = res.data.status;
         this.picking.pdfStatus = res.data.pdfStatus;
         this.picking.currentNum = res.data.currentNum;
         this.picking.totalNum = res.data.totalNum;
         this.picking.canShipping = res.data.canShipping;
         this.picking.isKnowFail = res.data.isKnowFail;
         this.picking.failStatus = res.data.failStatus;
         this.picking.pickingLogisticsType = res.data.pickingLogisticsType;
         this.defaultLogisticsType = res.info.defaultLogisticsType;
         this.integratedLogisticsSettingData = res.info.integratedLogisticsSettingData;
         this.logisticsErrorMsgArr = res.info.logisticsErrorMsgArr;
         this.detailData = res.info.data;
         this.failOrders = res.info.failOrders;

       });
      this.interval = setInterval(() => {
       getPickingInfo(row.pickingNo).then((res) => {
          //订单状态为1时跳转
          if (this.picking.status==1) {
            this.printPickShipping(res.data.pickingNo)
            this.lableDialogVisible=false;
             clearInterval(this.interval);
            return;
          }
          if(this.picking.failStatus==1){
             this.lableDialogVisible=false;
             clearInterval(this.interval);
          }

         this.picking.id = res.data.id;
         this.picking.pickingNo = res.data.pickingNo;
         this.picking.status = res.data.status;
         this.picking.pdfStatus = res.data.pdfStatus;
         this.picking.currentNum = res.data.currentNum;
         this.picking.totalNum = res.data.totalNum;
         this.picking.canShipping = res.data.canShipping;
         this.picking.isKnowFail = res.data.isKnowFail;
         this.picking.failStatus = res.data.failStatus;
         this.picking.pickingLogisticsType = res.data.pickingLogisticsType;
         this.defaultLogisticsType = res.info.defaultLogisticsType;
         this.integratedLogisticsSettingData = res.info.integratedLogisticsSettingData;
         this.logisticsErrorMsgArr = res.info.logisticsErrorMsgArr;
         this.detailData = res.info.data;
         this.failOrders = res.info.failOrders;

       });
      }, 6000);
    },
    // 打印拣货单的面单
    printPickShipping(pickingNo) {
      this.shippingPDFLoading = true;
      printPickShipping(pickingNo).then((res) => {
        this.shippingPDFLoading = false;

        if (res.type === 'application/json') {
          this.$errorMessage('系统繁忙，请稍后再试');
          console.log(res);
          let reader = new FileReader(); // 创建读取文件对象
          reader.readAsText(res, 'utf-8'); // 设置读取的数据以及返回的数据类型为utf-8
          reader.addEventListener('loadend', function () {
            //
            let res = JSON.parse(reader.result); // 返回的数据
          });
          return;
        }

        const pdfFile = window.URL.createObjectURL(new Blob([res.data], { type: 'application/pdf' }));
        // 跳转页面预览
        window.open(pdfFile);
        // 60秒后释放
        setTimeout(() => {
          URL.revokeObjectURL(pdfFile); //释放URL对象
        }, 60000);

        // 刷新数据
        this.$store.dispatch('user/getInfo');

        this.getData();
      });
    },
    // 触发变更事件
    changeOption(is_search = false, type = ''){
      if (is_search === true) {
        //判断是否使用过搜索按钮
        this.is_search = true
      }
      if (type === 'clear') {
        if (this.is_search === false) {
          return
        } else {
          this.is_search = false
        }
      }
      this.queryParams.page = 1;
      this.getData()
    },
    handleSizeChange(val){
      this.queryParams.pageSize = val;
      this.queryParams.page = 1;
      this.getData();
    },
    //排序
    handleSortChange(column){
      this.queryParams.orderBy = ''
      this.queryParams.orderField = ''
      if(column.order){
        this.queryParams.orderBy = column.order
        this.queryParams.orderField = column.prop
        if (column.prop == 'skuNum') {
          this.queryParams.orderField = 'sku_num'
        } else if (column.prop == 'goodsNum') {
          this.queryParams.orderField = 'goods_num'
        }
      }
      this.changeOption()
    },
    jumpInfo(row){
      this.$router.push({
        name: 'packInfo',
        query: {
          'pickingNo' : row.pickingNo,
        }
      })
    },
    selectable(row){
      if (row.pickingLogisticsType === 2) {
        return false
      }
      return true;
    },
    handleSelectionChange(val){
      this.selectIds = [];
      this.selectRow = [];
      val.forEach(item=>{
        if (item.pickingLogisticsType === 2) {
          return false
        }
        this.selectIds.push(item.id)
        this.selectRow.push(item)
      })
    },
    tableRowClassName({row, rowIndex}){
      const index = this.selectIds.indexOf(row.id)
      if(index !== -1){
        return 'choose-row'
      }
      return '';
    },
    // 批量确认捡货
    batchSurePack(row = null){
      const postData = {
        pickIds: [],
      };
      if(row === null){
        postData.pickIds = this.selectIds;
      }else{
        postData.pickIds.push(row.id)
      }

      this.$alert(
        `<p>当前选中的拣货单中的所有商品<span style="color: #FF0000">（不包含异常）</span>已完成拣货？</p>`,
        '确认拣货（选中的订单）？',
        {
          dangerouslyUseHTMLString:true,
          // type:'warning',
          showCancelButton:true,
        }
      )
        .then(res=>{
          this.batchLoading = true;
          batchSurePicking(postData)
            .then(res=>{
              this.batchLoading = false;
              if(res.error === 0){
                this.$successMessage(res.message)
                this.getData()
                this.$store.dispatch('user/getInfo');
              }else{
                this.$errorMessage(res.message)
              }
            })
        })
        .catch(res=>{

        })
    },
    batchPickPDF(){
      this.printLoading = true;
      this.data.forEach(item=>{
        this.currentPDFForm.pickIds.some(pickId => {
          if(pickId === item.id){
            item.jhLoading = true
            return true
          }
        })
      })
      batchPickPDF(this.currentPDFForm)
        .then(res=>{
          this.printLoading = false;
          this.data.forEach(item=>{
            item.jhLoading = false
          })
          if(res.type === 'application/json'){
            this.$errorMessage('系统繁忙，请稍后再试');
            // this.$errorMessage('功能开发中...');
            return;
          }
          this.PDFDialog = false;
          this.currentPDFForm.pickIds = [];
          const pdfFile = window.URL.createObjectURL(
            new Blob([res.data], { type: "application/pdf" })
          );
          // 跳转页面预览
          window.open(pdfFile);
          // 60秒后释放
          setTimeout(()=>{
            URL.revokeObjectURL(pdfFile); //释放URL对象
          },60000 * 5)

        })
    },
    // 展示pdf选择框
    showPDFDialog(row = null){
      this.currentPDFForm.pickIds = [];
      if(row === null){
        this.currentPDFForm.pickIds;
        this.selectRow.forEach(item=>{
          this.currentPDFForm.pickIds.push(item.id)
        })
      }else{
        this.currentPDFForm.pickIds.push(row.id)
      }
      this.PDFDialog = true
      // this.batchPickPDF(postData)
    },
    downLoadShipping(row){
      row.shippingLoading = true
      printPickShipping(row.pickingNo)
        .then(res=>{
          row.shippingLoading = false;
          if(res.type === 'application/json'){
            this.$errorMessage('系统繁忙，请稍后再试');
            return;
          }

          const pdfFile = window.URL.createObjectURL(
            new Blob([res.data], { type: "application/pdf" })
          );
          // 跳转页面预览
          window.open(pdfFile);
          // 60秒后释放
          setTimeout(()=>{
            URL.revokeObjectURL(pdfFile); //释放URL对象
          },60000 * 5)

          // 刷新数据
          this.$store.dispatch('user/getInfo');

          this.getData()
        })
    },
    // 批量打印面单
    batchShipping(){
      this.$successMessage('批量打印面单中...')
      this.selectRow.forEach(item=>{
        if(item.canShipping){
          this.downLoadShipping(item)
        }
      })
    },
    changePlatform(){
      this.queryParams.page = 1;
      this.getData();
    },
    changeOrder(){
      this.$router.go(0) // 刷新当前页面
    },
  }
}
</script>
<style>

.el-table .choose-row {
  background: #F3F6F9;
}
.el-table .choose-row:hover{
  background: #F3F6F9;
}

</style>

<style scoped lang="scss">
.wrap {
  padding: 30px 30px;

  .header {
    display: flex;
    justify-content: space-between;
  }

  .content {
    padding: 0 0 0;
    margin-top: 20px;
  }
}
</style>
